﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityHFSM;

using moai_kun_v2;
using Unity.VisualScripting;
using Cysharp.Threading.Tasks;

[RequireComponent(typeof(PlayerInput))]
public class PlayerController : MonoBehaviour
{
    #region Unity 方法

    private void OnEnable()
    {
        InitPlayer();
        InitInput();
        OnAttack += UniTask.Action(_player.Attack);
    }

 
    private void OnDisable()
    {
        OnAttack -= UniTask.Action(_player.Attack);
    }

    public void Update()
    {
        UpdatePlayerLogic();
    }


    #endregion

    #region Input 输入
    private PlayerInput _playerInput;
    private Vector2 _moveInput;
    private bool _jumpInput;
    private bool _attackInput;
    private bool _reset;

    public Action OnAttack;
    
   

    private void InitInput() 
    {
        _playerInput =GetComponent<PlayerInput>();
    }
    public void MoveInput(InputAction.CallbackContext ctx) 
    {
        _moveInput=ctx.ReadValue<Vector2>();
    }
    public void JumpInput(InputAction.CallbackContext ctx) 
    {
        _jumpInput = ctx.ReadValueAsButton();
    }

    public void AttackInput(InputAction.CallbackContext ctx) 
    {
        _attackInput = ctx.ReadValueAsButton();
        OnAttack.Invoke();
    }
    public void ResetInput(InputAction.CallbackContext ctx) 
    {
       _reset = ctx.ReadValueAsButton();
    }
    
    #endregion

    #region 控制
    private MainActor _player;
    private void InitPlayer() 
    {
        _player = GetComponent<MainActor>();
    }

    private void UpdatePlayerLogic()
    {
        _player.UpdateAirStatus(_moveInput.x);

        if (_reset) 
        {
            Debug.Log("角色死亡");
            _player.Die();
        }

        if (_moveInput.y < 0)
        {
            _player.StartCrouch();
            if (_attackInput) 
            {
                _player.SetBomb();
            }
        }
        else if(_moveInput.y>=0)
        {
            _player.StopCrouch();
        }

        if (_jumpInput) 
        {
            _player.Jump();
        }
        else if (_moveInput.x != 0) 
        {
            _player.Move(_moveInput);
        }
        else
        {
            _player.StaticIdle();
        }
    }
    #endregion

   
}
